from PIL import Image
import numpy as np
import matplotlib.pyplot as plt


# 图像的二值化并转换成为numpy矩阵
def Binarization(filename):
    img = Image.open(filename)
    limg = img.convert('L')  # 转化成灰度图
    limg = limg.resize((32, 32))
    threshold = 100
    table = []
    for i in range(256):
        if i < threshold:
            table.append(1)
        else:
            table.append(0)
    photo = limg.point(table, '1')

    # 灰度转换结果
    plt.imshow(photo)
    plt.show()

    np.set_printoptions(threshold=np.inf)
    table = np.reshape(np.array(list(photo.getdata())), (32, 32))
    return table


def pack_vector_to_file(filename, vector):
    # 用write的方式打开文件，没有就自己创建
    file = open(filename, "w")
    # 遍历矩阵，将numpy读出
    for row in vector:
        for item in row:
            file.write(str(int(item)))  # numpyInt64->int->str
        file.write("\n")

    file.close()


if __name__ == '__main__':

    img_file_name = "workDigits/2.jpg"
    txt_file_name = "2.txt"

    # 得到二值化举证
    res = Binarization(img_file_name)
    # 保存到文件
    pack_vector_to_file(txt_file_name, res)